﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StockMatch.Service;
using StockMatch.Service.Entity;
using Titan;

namespace StockMatch.WebSite.Controllers
{
    public class LoginController : StockControllerBase
    {
        public ActionResult Index()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
            {
                ViewBag.ReturnUrl = Server.UrlDecode(Request.QueryString["ReturnUrl"]);
            }
            return View();
        }

        [HttpPost]
        public ActionResult Index(string userName, string passWord)
        {
            #region 条件判断
            var data = new { code = 0, message = "" };
            if (string.IsNullOrEmpty(userName))
            {
                data = new { code = 0, message = "用户名不能为空" };
                return Json(data);
            }
            if (string.IsNullOrEmpty(passWord))
            {
                data = new { code = 0, message = "密码不能为空" };
                return Json(data);
            }
            #endregion


            string existUserName = ServiceManager.UserService.IsExistUser(userName);
            if (string.IsNullOrEmpty(existUserName))
            {
                data = new { code = 0, message = "用户名或密码错误" };
                return Json(data);
            }
            int loginError = ServiceManager.UserService.GetError(existUserName);

            if (loginError >= 4 && !string.IsNullOrEmpty(existUserName))
            {
                ServiceManager.UserService.CacheUser(existUserName);
                int timer = ServiceManager.UserService.GetTime(existUserName);
                if (timer <= 0)
                {
                    ServiceManager.UserService.RemoveCacheUser(existUserName);
                    ServiceManager.UserService.RemoveCacheUserError(existUserName);
                    loginError = 0;
                }
                if (timer > 0)
                {
                    data = new { code = 4, message = "登录错误次数过多，请于" + timer + "分钟后重试" };
                    return Json(data);
                }
            }


            #region 查询
            passWord = Encryption.GetMD5HashHex(passWord);
            QueryExpression query = new QueryExpression();
            query.EntityType = typeof(User);
            query.Selects.Add(User_.UserId);
            query.Selects.Add(User_.UserName);
            query.Selects.Add(User_.BalanceAmount);
            query.Selects.Add(User_.TotalAmount);
            query.Selects.Add(User_.UserState);

            //用户名
            ConditionExpressionCollection c1 = new ConditionExpressionCollection();
            c1.ConditionRelation = ConditionRelation.And;
            c1.Add(User_.UserName.TEqual(userName));
            c1.Add(User_.UserPassword.TEqual(passWord));

            //手机
            ConditionExpressionCollection c2 = new ConditionExpressionCollection();
            c2.ConditionRelation = ConditionRelation.And;
            c2.Add(User_.Phone.TEqual(userName));
            c2.Add(User_.UserPassword.TEqual(passWord));

            //邮箱
            ConditionExpressionCollection c3 = new ConditionExpressionCollection();
            c3.ConditionRelation = ConditionRelation.And;
            c3.Add(User_.Email.TEqual(userName));
            c3.Add(User_.UserPassword.TEqual(passWord));

            query.Wheres.ConditionRelation = ConditionRelation.Or;
            query.Wheres.Add(c1);
            query.Wheres.Add(c2);
            query.Wheres.Add(c3);

            Users users = ServiceManager.UserService.GetUsers(query);
            #endregion

            if (users != null && users.Items.Count > 0)
            {
                User user = users.Items[0];
                if (user.UserState == 3)
                {
                    data = new { code = 3, message = "账号已锁定，请联系客服" };
                    return Json(data);//账号锁定
                }
                CurrentUser currentUser = new CurrentUser();
                currentUser.UserId = user.UserId;
                currentUser.UserName = user.UserName;
                Response.SetCookie(WebConfig.CookieName, user);

                data = new { code = 1, message = "登录成功" };
                return Json(data);
            }
            ServiceManager.UserService.CacheUserError(existUserName);
            data = new { code = 0, message = "用户名或密码错误" };
            if (loginError >= 2)
            {
                data = new { code = 0, message = "登录次数过多，您还有" + (4 - loginError) + "次机会" };
            }
            return Json(data);
        }

        public ActionResult LoginOut()
        {
            Response.RemoveCookie(WebConfig.CookieName);
            return RedirectToAction("Index", "Home");
        }
    }
}